<template>
  <div class="form-currency flex-x">
    <!-- 金额 -->
    <el-input 
      autocomplete="off"
      ref="input" 
      type="number" 
      :id="`form_${field.fieldName}`"
      :placeholder="t('common.placeholder.inputCurrency')" 
      v-model="value.number"
      @blur="blurChange"
      :disabled="disabled"
    />

    <!-- 货币 -->
    <el-select v-model="currentCurrency"  :disabled="disabled" @change="selectChange" class="mar-l-4">
      <el-option 
        v-for="item in currentOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>
</div>
</template>

<script>
import { findComponentUpward } from '@src/util/assist';
import FormMixin from '@src/component/form/mixin/form';
import { currencyOption, validateCurrencyNumber } from '@src/util/currency';
import { isEmpty } from '@src/util/type'

export default {
  name: 'form-currency',
  mixins: [FormMixin],
  props: {
    value: {
      type: Object,
      default: () => {
        return {
          number: '',
          currency: ''
        }
      }
    }
  },
  data() {
    return {
      currentCurrency: this.value?.currency || this.field?.setting?.defaultCurrency,
      currentOptions: currencyOption || []
    }
  },
  watch: {
    value(newV){
      if(newV?.currency) this.currentCurrency = newV?.currency;
    }
  },
  created() {
  },
  methods: {
    update(newValue) {
      this.$emit('update', { newValue, field: this.field });
      this.$emit('input', newValue);
    },

    blurChange(event) {
      let number = validateCurrencyNumber(event.target.value, this);
      this.update({ number, currency: this.value.currency});
    },

    selectChange(currency) {
      this.update({ number: this.value.number, currency});
      this.$nextTick(() => {
        // 如果存在计算公式涉及当前金额字段，切换币种时需要重新触发币种是否统一的校验
        let isNeedValidate = false;
        let parent = findComponentUpward(this, 'form-builder');
        let formulaFields = (parent?.fields || []).filter(item => item.formType === 'formula');
        
        // 判断所有的计算公式是否关联当前的金额字段
        isNeedValidate = formulaFields && formulaFields.some(item => {
          return !isEmpty(item.setting.formula) && item.setting.formula.some(f => !f.isOperator && f.value === this.field.fieldName);
        });

        if(isNeedValidate) parent.validate();
      })
    }
  }
}
</script>

<style lang="scss">
.form-currency {
  width: 100%;

  input {
    width: 100%;

    &:disabled {
      -webkit-text-fill-color: #BFBFBF;
      border-color: #D9D9D9;
      background-color: #f5f5f5;

      &:hover {
        border-color: #D9D9D9;
      }
    }
  }
  .el-select {
    width: 40%;
  }
}
</style>
